<template>
  <div class="login-container">
    <div class="login-box">
      <h2>简历生成器</h2>
      <p class="subtitle">登录您的账户</p>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名或邮箱"
            size="large"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            size="large"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="register-link">
        还没有账户？
        <router-link to="/register">立即注册</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { login as loginApi } from '@/api/auth'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

const loginFormRef = ref(null)

const handleLogin = async () => {
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true
    
    console.log('尝试登录，用户名:', loginForm.username)
    
    try {
      // 优先尝试后端API登录
      const response = await loginApi({
        username: loginForm.username,
        password: loginForm.password
      })
      
      console.log('后端登录响应:', response)
      
      // 处理成功响应
      let token, user
      if (response.token) {
        token = response.token
        user = response.user || { username: loginForm.username }
      } else if (response.data?.token) {
        token = response.data.token
        user = response.data.user || { username: loginForm.username }
      } else {
        throw new Error('登录响应格式错误')
      }
      
      // 保存用户信息和token
      authStore.setToken(token)
      authStore.setUser(user)
      
      ElMessage.success('登录成功')
      console.log('准备跳转到dashboard')
      await router.push('/dashboard')
      
    } catch (apiError) {
      console.error('后端API登录失败:', apiError)
      
      if (apiError.response?.status === 500) {
        const errorMsg = apiError.response.data?.message || '服务器错误'
        if (errorMsg.includes('用户不存在')) {
          ElMessage.error('用户不存在，请先注册或联系管理员')
        } else {
          ElMessage.error(`登录失败: ${errorMsg}`)
        }
      } else if (apiError.response?.status === 401) {
        ElMessage.error('用户名或密码错误')
      } else if (apiError.code === 'ECONNREFUSED' || apiError.message?.includes('Network Error')) {
        ElMessage.warning('无法连接到后端服务，使用模拟登录进行测试')
        
        // 模拟登录成功（仅用于前端功能测试）
        const mockToken = 'mock_token_' + Date.now()
        const mockUser = { 
          id: 1,
          username: loginForm.username,
          email: loginForm.username.includes('@') ? loginForm.username : `${loginForm.username}@example.com`
        }
        
        authStore.setToken(mockToken)
        authStore.setUser(mockUser)
        
        ElMessage.success('模拟登录成功（仅用于测试）')
        await router.push('/dashboard')
      } else {
        ElMessage.error('登录失败，请重试')
      }
    }
    
  } catch (error) {
    console.error('登录过程出错:', error)
    ElMessage.error('登录过程出错，请重试')
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  width: 400px;
}

h2 {
  text-align: center;
  margin-bottom: 10px;
  color: #333;
}

.subtitle {
  text-align: center;
  color: #666;
  margin-bottom: 30px;
}

.login-form {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
}

.register-link {
  text-align: center;
  color: #666;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style> 